package com.rent.auth.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rent.auth.pojo.AdminExtension;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.util.CollectionUtils;

import java.util.LinkedHashMap;

/**
 * @Author zhang
 * @create 2021/8/18 15:47
 */
@Slf4j
public class CustomJwtAccessTokenConverter extends JwtAccessTokenConverter {


    @Autowired
    private UserDetailsService userDetailsService;


    @SuppressWarnings("unchecked")
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        if (accessToken == null) {
            return super.enhance(accessToken, authentication);
        }
        // 开始刷新token
        if (accessToken.getRefreshToken() != null) {
            log.info("刷新token:{}", accessToken);
            return super.enhance(accessToken, authentication);
        }
        boolean isRefresh = super.isRefreshToken(accessToken);
        log.info("是否刷新token:{}", isRefresh);
        if (isRefresh) {
            return super.enhance(accessToken, authentication);
        }
        String name = authentication.getName();
        log.info("获取token信息名称:{}", name);
        Object principal = authentication.getPrincipal();
        AdminExtension data;
        if (principal instanceof AdminExtension) {
            data = (AdminExtension) principal;
        } else {
            //refresh_token默认不去调用userdetailService获取用户信息
            UserDetails userDetails = userDetailsService.loadUserByUsername(name);
            if (userDetails == null) return null;
            data = (AdminExtension) userDetails;
        }
        LinkedHashMap<String, Object> map = JSONObject.parseObject(JSON.toJSONString(data), LinkedHashMap.class);
        if (CollectionUtils.isEmpty(map)) return null;
//        log.info("获取token转化信息:" + map);
        // 转化 authorities 中的列表数据类型
        if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
            map.put("authorities", AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
        }
//        map.put("user_name", name);
        DefaultOAuth2AccessToken defaultOAuth2AccessToken = (DefaultOAuth2AccessToken) accessToken;
        defaultOAuth2AccessToken.setAdditionalInformation(map);
        return super.enhance(accessToken, authentication);
    }
}
